package com.cz.nongyetongv5.activity;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.wheelview.Utils;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ImageUtil;

public class YongHuActivity extends Fragment {

	/**
	 * 去拍照
	 */
	private static final int TO_CAMERA = 1;

	/**
	 * 去相册里选择
	 */
	private static final int TO_PICK = 2;

	/**
	 * 裁剪
	 */
	private static final int TO_ZOOM = 3;

	/**
	 * 用户对象
	 */
	private User user = null;

	/**
	 * 用户头像
	 */
	private ImageView ivUserPhoto = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {

		return inflater.inflate(R.layout.usercenter, null);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putSerializable("user", user);

		Log.d("savestate", "user input ~~");

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		final Activity activity = getActivity();

		Intent intent = activity.getIntent();

		Log.d("savestate", "onActivityCreated~~");

		if (intent != null) {

			user = (User) intent.getSerializableExtra("user");

			Log.d("savestate", "from intent~~");

		} else {

			Log.d("savestate", "savedInstanceState~~");

			if (savedInstanceState != null) {
				user = (User) savedInstanceState.getSerializable("user");
				Log.d("savestate", "savedInstanceState~~ user");
			}

		}

		EditText edtShowName = (EditText) activity
				.findViewById(R.id.edtShowName);

		EditText edtUserInfo = (EditText) activity
				.findViewById(R.id.edtUserInfo);

		Button btnLoginout = (Button) activity.findViewById(R.id.btnLoginout);

		if (user != null && CharsetUtil.isNotNull(user.getUsername())) {
			edtUserInfo.setText("当前用户 : " + user.getUsername());

			edtShowName.setText("昵称 : " + user.getShowname());

			btnLoginout.setVisibility(View.VISIBLE);

			btnLoginout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					final CustomDialog exitDialog = new CustomDialog(activity);

					exitDialog.setOnCancleClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							exitDialog.dismiss();
						}
					});

					exitDialog.setOnActionClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							// 确定注销

							// 清除数据分享
							SharedPreferences sharedData = activity
									.getSharedPreferences(
											CommonConstants.SHARED_REFERENCES_TAG,
											Context.MODE_PRIVATE);

							Editor editor = sharedData.edit();

							editor.remove("username");

							editor.remove("password");

							editor.remove("town_path_id");

							editor.remove("showname");

							editor.remove("localpysimple");

							editor.remove("region_longitude");

							editor.remove("region_latitude");

							editor.remove("region_zoom");

							// 提交数据修改
							editor.commit();

							Intent to_login = new Intent(activity,
									LoginActivity.class);

							startActivity(to_login);

							activity.finish();

						}
					});

					exitDialog.setNote("确定，注销当前登录用户，下次打开APP时需输入用户名和密码；");

					exitDialog.setMessage(getResources().getString(
							R.string.loginout_message));

					exitDialog.setCancleTxt(getResources().getString(
							R.string.jiandujiancha_item_cancle));

					exitDialog.setActionTxt(getResources().getString(
							R.string.jiandujiancha_item_sure));

					exitDialog.show();
				}
			});
		} else {
			edtUserInfo.setText("当前用户 : 获取用户信息异常");
			btnLoginout.setVisibility(View.GONE);
		}

		ivUserPhoto = (ImageView) getActivity().findViewById(R.id.ivUserPhoto);

		/**
		 * 当头像点击的时候
		 */
		ivUserPhoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				final AlertDialog bottomWindow = new AlertDialog.Builder(
						new ContextThemeWrapper(getActivity(),
								R.style.NongYeTongFullscreenTheme)).create();

				// 输入法的设置
				bottomWindow.getWindow().setFlags(
						WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
						WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

				// 设置窗口的动画
				bottomWindow.getWindow().setWindowAnimations(
						R.style.bottomAnimStyle);

				bottomWindow.show();

				/**
				 * 选择头像
				 */
				ViewGroup bottomLayout = (ViewGroup) getActivity()
						.getLayoutInflater().inflate(
								R.layout.bottom_jianchaneirong, null);

				ViewGroup vgTitle = (ViewGroup) bottomLayout
						.findViewById(R.id.bottonRelativeLayout);

				bottomLayout.removeView(vgTitle);

				// 让底部的宽度和屏幕的宽度一致
				bottomLayout.setMinimumWidth(getActivity().getWindowManager()
						.getDefaultDisplay().getWidth());

				// 设置底部布局
				bottomWindow.setContentView(bottomLayout);

				// 弹出输入法的操作
				bottomWindow.getWindow().clearFlags(
						WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

				bottomWindow.getWindow().setGravity(Gravity.BOTTOM);

				/**
				 * 进行视图的动态生成
				 */
				LinearLayout jianChaNeiRongLayout = (LinearLayout) bottomLayout
						.findViewById(R.id.jianchaneironglayout);

				jianChaNeiRongLayout.setGravity(Gravity.CENTER_VERTICAL);

				jianChaNeiRongLayout.setMinimumHeight(0);

				// 清理视图
				jianChaNeiRongLayout.removeAllViews();

				// 每一项的String
				String[] itemString = { "拍照", "从相册选择头像", "取消" };

				OnClickListener itemOnClickListener = new OnClickListener() {

					@Override
					public void onClick(View v) {

						bottomWindow.dismiss();

						Integer position = (Integer) v.getTag();

						if (position == 0) {

							File file = new File(ImageUtil.getUserPhotoDir(),
									user.getUsername() + ".jpg");

							// 拍照
							Intent intent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);

							// 下面这句指定调用相机拍照后的照片存储的路径
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(file));

							startActivityForResult(intent, TO_CAMERA);

						} else if (position == 1) {

							/**
							 * 选择系统图片 　　
							 */
							Intent intent = new Intent(Intent.ACTION_PICK, null);
							intent.setDataAndType(
									MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
									"image/*");

							startActivityForResult(intent, TO_PICK);
						}

					}
				};

				// 遍历检查行业进行视图的生成
				for (int i = 0; i < itemString.length; i++) {

					String temp = itemString[i];

					final RelativeLayout rootLayout = new RelativeLayout(
							getActivity());

					rootLayout.setTag(i);

					// 点击每一项的监听
					rootLayout.setOnClickListener(itemOnClickListener);

					MarginLayoutParams rootLayoutPrams = new MarginLayoutParams(
							MarginLayoutParams.MATCH_PARENT,
							MarginLayoutParams.WRAP_CONTENT);

					if (i == 2) {

						rootLayoutPrams.setMargins(0,
								Utils.dip2px(getActivity(), 6), 0,
								Utils.dip2px(getActivity(), 4));
					} else {
						rootLayoutPrams.setMargins(0,
								Utils.dip2px(getActivity(), 4), 0,
								Utils.dip2px(getActivity(), 4));
					}

					// 兼容低版本设置margin方法
					LayoutParams layoutPrarams = new LayoutParams(
							rootLayoutPrams);
					layoutPrarams.gravity = Gravity.TOP | Gravity.LEFT;

					rootLayout.setLayoutParams(layoutPrarams);
					rootLayout.setClickable(true);

					rootLayout.setPadding(0, Utils.dip2px(getActivity(), 3), 0,
							Utils.dip2px(getActivity(), 3));

					rootLayout
							.setBackgroundResource(R.drawable.jiandujiancha_item_style);

					/*********************************************/

					TextView tvBeiJianChaHangYe = new TextView(getActivity());

					RelativeLayout.LayoutParams tvBeiJianChaHangYeLayout = new RelativeLayout.LayoutParams(
							RelativeLayout.LayoutParams.WRAP_CONTENT,
							RelativeLayout.LayoutParams.WRAP_CONTENT);
					tvBeiJianChaHangYeLayout
							.addRule(RelativeLayout.CENTER_IN_PARENT);
					tvBeiJianChaHangYe
							.setLayoutParams(tvBeiJianChaHangYeLayout);

					tvBeiJianChaHangYe.setPadding(
							Utils.dip2px(getActivity(), 4),
							Utils.dip2px(getActivity(), 8),
							Utils.dip2px(getActivity(), 4),
							Utils.dip2px(getActivity(), 8));

					if (i == 2) {

						tvBeiJianChaHangYe.setTextColor(Color.RED);
					} else {
						tvBeiJianChaHangYe.setTextColor(Color
								.parseColor("#656769"));
					}

					tvBeiJianChaHangYe.setTextSize(16);
					tvBeiJianChaHangYe.setText(temp);

					rootLayout.addView(tvBeiJianChaHangYe);

					jianChaNeiRongLayout.addView(rootLayout);

				}

			}
		});

		final Handler handler = new Handler() {

			public void handleMessage(Message msg) {

				switch (msg.what) {
					case 1:

						Object userPhoto = msg.obj;

						if (userPhoto != null) {

							ivUserPhoto.setImageBitmap((Bitmap) userPhoto);

						}

						break;

					default:
						break;
				}

			};

		};

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == TO_CAMERA && resultCode == Activity.RESULT_OK) {

			File file = new File(ImageUtil.getUserPhotoDir(),
					user.getUsername() + ".jpg");

			if (file.exists()) {
				zoomPhoto(Uri.fromFile(file));
			}

		}

		if (requestCode == TO_PICK && resultCode == Activity.RESULT_OK) {

			zoomPhoto(data.getData());

		}

		if (requestCode == TO_ZOOM && resultCode == Activity.RESULT_OK) {

			if (data != null && data.getExtras() != null
					&& data.getExtras().getParcelable("data") != null) {

				final Bitmap photo = data.getExtras().getParcelable("data");

				final CustomDialog wait = new CustomDialog(getActivity());

				wait.setMessage("正在上传头像...");

				wait.showWait();

				final Handler handler = new Handler() {

					@Override
					public void handleMessage(Message msg) {

						switch (msg.what) {
							case 1:
								wait.dismiss();
								ivUserPhoto.setImageBitmap(photo);
								break;

							default:
								break;
						}

					}

				};

			} else {

				Toast.makeText(getActivity(), "裁剪图片失败...", Toast.LENGTH_SHORT)
						.show();

			}
		}

	}

	/**
	 * 去裁剪页面
	 */
	private void zoomPhoto(Uri uri) {

		int widOrHei = Utils.dip2px(getActivity(), 100);

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", widOrHei);
		intent.putExtra("outputY", widOrHei);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, TO_ZOOM);

	}

}
